﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UdrinkWater_Project.Officer
{
    public partial class ManuFacture : System.Web.UI.Page
    {
        private string Connection = ConfigurationManager.ConnectionStrings["DB_Udrink"].ConnectionString;
        private ManuFacDataContext db = new ManuFacDataContext();
        public static DataTable dtManuList = new DataTable();
        public static DataTable dtMatList = new DataTable();
        public static int dtConut = 0;
        public static DateTime Order_Date_ID;
        public static string OrderID;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Order_Date_ID = DateTime.Now;
                OrderID = Order_Date_ID.ToString("yyyy-MM-dd HH:mm:ss.fff",new System.Globalization.CultureInfo("en-US"));
                dtManuList = new DataTable();
                dtMatList = new DataTable();
                string T1 = Order_Date_ID.ToString("dd/MM/yyyy", new System.Globalization.CultureInfo("th-TH"));
                string T2 = Order_Date_ID.ToString("HH:mm:ss", new System.Globalization.CultureInfo("en-US"));
                string T3 = Order_Date_ID.ToString("yyyy-MM-dd", new System.Globalization.CultureInfo("en-US"));
                txtStockDate.Text = T1 + " " + T2;
            }
            else
            {

            }
        }

        private DataTable GetInstock(string Product_ID)
        {
            string sqltext = @"SELECT        Product_ID, Product_Count
                               FROM          TB_StockProductIN
                               WHERE         Product_ID = '" + Product_ID + "' ";
            SqlConnection sqlconn = new SqlConnection(Connection);
            SqlDataAdapter da = new SqlDataAdapter(sqltext, sqlconn);
            DataSet ds = new DataSet();
            da.Fill(ds);

            return ds.Tables[0];
        }

        private DataTable GetOutstock(string Product_ID)
        {
            string sqltext = @"SELECT        Product_ID, Product_Count
                               FROM          TB_StockProductOUT
                               WHERE         Product_ID = '" + Product_ID + "' ";
            SqlConnection sqlconn = new SqlConnection(Connection);
            SqlDataAdapter da = new SqlDataAdapter(sqltext, sqlconn);
            DataSet ds = new DataSet();
            da.Fill(ds);

            return ds.Tables[0];
        }

        private DataTable GetDetialPro(string Product_ID)
        {
            string sqltext = @"SELECT TB_Product.Product_ID, TB_Product.Product_name, TB_Unit_Category.Unit_Name, 
                               TB_Product.Price, TB_Product.In_Stock, TB_Product.Image_Path 
                               FROM TB_Product LEFT JOIN TB_Unit_Category ON TB_Product.Unit = TB_Unit_Category.Unit_ID
                               WHERE TB_Product.Product_ID ='" + Product_ID + "' ";
            SqlConnection sqlconn = new SqlConnection(Connection);
            SqlDataAdapter da = new SqlDataAdapter(sqltext, sqlconn);
            DataSet ds = new DataSet();
            da.Fill(ds);

            return ds.Tables[0];

        }
       

        protected void btSaveAndReport_Click(object sender, EventArgs e)
        {
            if (dtManuList != null && dtManuList.Rows.Count > 0)
            {
                DataTable dt = new DataTable();
                dt = dtManuList;
                DataTable mt = new DataTable();
                mt = dtMatList;
                DataTable FindEmp;
                FindEmp = GetDetialEmp(txtEmpID.Text);
                string T1 = Order_Date_ID.ToString("yyyy-MM-dd", new System.Globalization.CultureInfo("en-US"));
                string T2 = Order_Date_ID.ToString("HH:mm:ss.fff", new System.Globalization.CultureInfo("en-US"));
                if (txtEmpID.Text == "" || FindEmp.Rows.Count == 0)
                {
                     lbWarnEmp.Visible = true;
                }
                else
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        string sqltext = @"INSERT INTO [TB_Manufacture]
                                                   ([Manu_Date]
                                                   ,[Product_ID]
                                                   ,[Product_Count]
                                                   ,[Act_Officer]
                                                   ,[Status_Manufacture]) 
                                    VALUES (@Manu_Date,@Product_ID,@Product_Count,@Act_Officer,@Status_Manufacture)";
                        SqlCommand sqlcomm = new SqlCommand();
                        SqlConnection sqlconn = new SqlConnection(Connection);
                        sqlcomm.Connection = sqlconn;
                        sqlcomm.CommandType = System.Data.CommandType.Text;
                        sqlcomm.CommandText = sqltext;
                        sqlcomm.Parameters.AddWithValue("@Manu_Date", OrderID);
                        sqlcomm.Parameters.AddWithValue("@Product_ID",dt.Rows[i]["Product_ID"].ToString());
                        sqlcomm.Parameters.AddWithValue("@Product_Count", Convert.ToInt32(dt.Rows[i]["Count"].ToString()));
                        sqlcomm.Parameters.AddWithValue("@Act_Officer", txtEmpID.Text);
                        sqlcomm.Parameters.AddWithValue("@Status_Manufacture", 1);
                        try
                        {
                            sqlcomm.Connection.Open();
                            sqlcomm.ExecuteNonQuery();
                        }
                        catch (Exception)
                        {
                            sqlcomm.Connection.Close();
                            sqlcomm.Connection.Dispose();
                        }
                        sqlcomm.Connection.Close();
                        sqlcomm.Connection.Dispose();
                    }
                    if (dtMatList != null && dtMatList.Rows.Count > 0)
                    {
                        
                        for (int i = 0; i < mt.Rows.Count; i++)
                        {
                            string sqltext = @"INSERT INTO [TB_ManufactureM_List]
                                                    ([Manu_M_Date]
                                                    ,[Material_ID]
                                                    ,[Material_Count])  
                                    VALUES (@Manu_M_Date,@Material_ID,@Material_Count)";
                            SqlCommand sqlcomm = new SqlCommand();
                            SqlConnection sqlconn = new SqlConnection(Connection);
                            sqlcomm.Connection = sqlconn;
                            sqlcomm.CommandType = System.Data.CommandType.Text;
                            sqlcomm.CommandText = sqltext;
                            sqlcomm.Parameters.AddWithValue("@Manu_M_Date", OrderID);
                            sqlcomm.Parameters.AddWithValue("@Material_ID", mt.Rows[i]["MatID"].ToString());
                            sqlcomm.Parameters.AddWithValue("@Material_Count", Convert.ToInt32(mt.Rows[i]["Count"].ToString()));
                            try
                            {
                                sqlcomm.Connection.Open();
                                sqlcomm.ExecuteNonQuery();
                            }
                            catch (Exception)
                            {
                                sqlcomm.Connection.Close();
                                sqlcomm.Connection.Dispose();
                            }
                            sqlcomm.Connection.Close();
                            sqlcomm.Connection.Dispose();
                        }
                      
                    }
                    Session["list"] = (dtManuList.Rows.Count).ToString();
                    Session["ManuDateID"] = T1 + " " + T2;
                    Session["EmpID"] = txtEmpID.Text;
                    Session["EmpName"] = txtEmpName.Text;
                    Response.Write("<script>alert('บันทึกรายการเรียบร้อยแล้ว!');</script>");
                    Response.Redirect("BillManu.aspx");
                    


                }

            }
        }

        protected void ASPxGridView4_RowCommand(object sender,DevExpress.Web.ASPxGridView.ASPxGridViewRowCommandEventArgs e)
        {
            DataTable DataPro = new DataTable();
            DataTable InStock = new DataTable();
            DataTable OutStock = new DataTable();
            if (e.CommandArgs.CommandName == "Cmd_Select")
            {
                string Id = e.CommandArgs.CommandArgument.ToString();
                DataPro = GetDetialPro(Id);
                InStock = GetInstock(Id);
                OutStock = GetOutstock(Id);
                int NumIN = 0;
                int NumOUT = 0;
                for (int i = 0; i < InStock.Rows.Count; i++)
                {

                    NumIN = NumIN + Convert.ToInt32(InStock.Rows[i]["Product_Count"].ToString());
                }
                for (int i = 0; i < OutStock.Rows.Count; i++)
                {
                    NumOUT = NumOUT + Convert.ToInt32(OutStock.Rows[i]["Product_Count"].ToString());
                }
                txtProductId.Text = DataPro.Rows[0]["Product_ID"].ToString();
                txtProductName.Text = DataPro.Rows[0]["Product_name"].ToString();
                txtInStock.Text = (NumIN - NumOUT).ToString();
                txtUnit.Text = DataPro.Rows[0]["Unit_Name"].ToString();

                txtCount.Focus();
            }
        }

        protected void ASPxGridView2_RowCommand(object sender,DevExpress.Web.ASPxGridView.ASPxGridViewRowCommandEventArgs e)
        {
            DataTable DataEmp = new DataTable();
            if (e.CommandArgs.CommandName == "Cmd_Select")
            {
                string Id = e.CommandArgs.CommandArgument.ToString();
                DataEmp = GetDetialEmp(Id);
                txtEmpID.Text = DataEmp.Rows[0]["ID_Card"].ToString();
                txtEmpName.Text = DataEmp.Rows[0]["Name"].ToString();
            }
        }

        private DataTable GetDetialEmp(string ID_Card)
        {
            string sqltext = @"SELECT ID_Card,( Prefix + '' + Firstname + ' ' + Lastname ) AS Name FROM TB_Employee
                               WHERE [ID_Card] ='" + ID_Card + "' ";
            SqlConnection sqlconn = new SqlConnection(Connection);
            SqlDataAdapter da = new SqlDataAdapter(sqltext, sqlconn);
            DataSet ds = new DataSet();
            da.Fill(ds);

            return ds.Tables[0];

        }

        protected void btAddList_Click(object sender, EventArgs e)
        {
            lbWranList.Visible = false;
            
            if (dtManuList != null && dtManuList.Rows.Count == 0)
            {
                DataRow drManuRow = null;
                if (dtConut == 0)
                {
                    dtManuList = new DataTable();
                    dtManuList.Columns.Add(new DataColumn("Product_ID", typeof (string)));
                    dtManuList.Columns.Add(new DataColumn("Product_Name", typeof (string)));
                    dtManuList.Columns.Add(new DataColumn("Unit", typeof (string)));
                    dtManuList.Columns.Add(new DataColumn("Count", typeof (int)));

                }
                else
                {
                    dtManuList = new DataTable();
                    dtManuList.Columns.Add(new DataColumn("Product_ID", typeof (string)));
                    dtManuList.Columns.Add(new DataColumn("Product_Name", typeof (string)));
                    dtManuList.Columns.Add(new DataColumn("Unit", typeof (string)));
                    dtManuList.Columns.Add(new DataColumn("Count", typeof (int)));

                }

                drManuRow = dtManuList.NewRow();
                drManuRow["Product_ID"] = txtProductId.Text;
                drManuRow["Product_Name"] = txtProductName.Text;
                drManuRow["Unit"] = txtUnit.Text;
                drManuRow["Count"] = Int32.Parse(txtCount.Text);

                dtManuList.Rows.Add(drManuRow);
                GV_OrderList.DataSource = dtManuList;
                GV_OrderList.DataBind();
                dtConut = 1;
                //Session["TablePrice"] = dtOrderList;
            }
            else if (dtManuList != null && dtManuList.Rows.Count > 0)
            {
                dtConut = 0;
                for (int i = 0; i < dtManuList.Rows.Count; i++)
                {
                    if (dtManuList.Rows[i]["Product_ID"].ToString() == txtProductId.Text)
                    {
                        dtConut = 1;
                    }
                }
                if (dtConut != 1)
                {
                    DataRow drStockRow = dtManuList.NewRow();
                    drStockRow["Product_ID"] = txtProductId.Text;
                    drStockRow["Product_Name"] = txtProductName.Text;
                    drStockRow["Unit"] = txtUnit.Text;
                    drStockRow["Count"] = Int32.Parse(txtCount.Text);

                    dtManuList.Rows.Add(drStockRow);
                    GV_OrderList.DataSource = dtManuList;
                    GV_OrderList.DataBind();
                    //Session["TablePrice"] = dtOrderList;
                }

            }
            txtProductId.Text = "";
            txtProductName.Text = "";
            txtInStock.Text = "";
            txtCount.Text = "";
            txtUnit.Text = "";

        }

        protected void ASPxButton1_Click(object sender, EventArgs e)
        {
            if (dtMatList != null && dtMatList.Rows.Count == 0)
            {
                DataRow drMatRow = null;
                if (dtConut == 0)
                {
                    dtMatList = new DataTable();
                    dtMatList.Columns.Add(new DataColumn("MatID", typeof(string)));
                    dtMatList.Columns.Add(new DataColumn("Mat_Name", typeof(string)));
                    dtMatList.Columns.Add(new DataColumn("Unit", typeof(string)));
                    dtMatList.Columns.Add(new DataColumn("Count", typeof(int)));

                }
                else
                {
                    dtMatList = new DataTable();
                    dtMatList.Columns.Add(new DataColumn("MatID", typeof(string)));
                    dtMatList.Columns.Add(new DataColumn("Mat_Name", typeof(string)));
                    dtMatList.Columns.Add(new DataColumn("Unit", typeof(string)));
                    dtMatList.Columns.Add(new DataColumn("Count", typeof(int)));

                }

                drMatRow = dtMatList.NewRow();
                drMatRow["MatID"] = txtMatID.Text;
                drMatRow["Mat_Name"] = txtMatName.Text;
                drMatRow["Unit"] = txtMatU.Text;
                drMatRow["Count"] = Int32.Parse(txtMatCount.Text);

                dtMatList.Rows.Add(drMatRow);
                GV_OrderList0.DataSource = dtMatList;
                GV_OrderList0.DataBind();
                dtConut = 1;
                
            }
            else if (dtMatList != null && dtMatList.Rows.Count > 0)
            {
                dtConut = 0;
                for (int i = 0; i < dtMatList.Rows.Count; i++)
                {
                    if (dtMatList.Rows[i]["MatID"].ToString() == txtMatID.Text)
                    {
                        dtConut = 1;
                    }
                }
                if (dtConut != 1)
                {
                    DataRow drMatRow = dtMatList.NewRow();
                    drMatRow["MatID"] = txtMatID.Text;
                    drMatRow["Mat_Name"] = txtMatName.Text;
                    drMatRow["Unit"] = txtMatU.Text;
                    drMatRow["Count"] = Int32.Parse(txtMatCount.Text);

                    dtMatList.Rows.Add(drMatRow);
                    GV_OrderList0.DataSource = dtMatList;
                    GV_OrderList0.DataBind();
                    //Session["TablePrice"] = dtOrderList;
                }

            }
            txtMatID.Text = "";
            txtMatName.Text = "";
            txtMatU.Text = "";
            txtMatCount.Text = "";
            txtMatStock.Text = "";
        }

        protected void GV_OrderList0_RowCommand(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewRowCommandEventArgs e)
        {

            if (e.CommandArgs.CommandName == "Cmd_Delete")
            {
                // Response.Redirect("PromotionLogin.aspx");
                string Index = e.CommandArgs.CommandArgument.ToString();
                DataTable dt = dtMatList;
                dt.Rows[Convert.ToInt32(Index)].Delete();
                GV_OrderList0.DataSource = dt;
                GV_OrderList0.DataBind();
            }
        }

        protected void GV_OrderList_RowCommand(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewRowCommandEventArgs e)
        {
            if (e.CommandArgs.CommandName == "Cmd_Delete")
            {
                // Response.Redirect("PromotionLogin.aspx");
                string Index = e.CommandArgs.CommandArgument.ToString();
                DataTable dt = dtManuList;
                dt.Rows[Convert.ToInt32(Index)].Delete();
                GV_OrderList.DataSource = dt;
                GV_OrderList.DataBind();
            }
        }

        protected void GV_OrderList_SummaryDisplayText(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewSummaryDisplayTextEventArgs e)
        {

        }

        protected void GV_OrderList_FocusedRowChanged(object sender, EventArgs e)
        {

        }

       

        protected void btNewOrder_Click(object sender, EventArgs e)
        {
            dtManuList = new DataTable();
            dtMatList = new DataTable();
            Response.Redirect("ManuFacture.aspx.aspx");
        }

        
        private DataTable GetInstockMat(string Mat_ID)
        {
            string sqltext = @"SELECT [Material_ID]
                            ,[Material_Count]      
                             FROM [TB_Material_StockIN]
                             WHERE         Material_ID = '" + Mat_ID + "' ";
            SqlConnection sqlconn = new SqlConnection(Connection);
            SqlDataAdapter da = new SqlDataAdapter(sqltext, sqlconn);
            DataSet ds = new DataSet();
            da.Fill(ds);

            return ds.Tables[0];
        }

        private DataTable GetOutstockMat(string Mat_ID)
        {
            string sqltext = @"SELECT [Material_ID]
                               ,[Material_Count]      
                               FROM [TB_Material_StockOUT]
                               WHERE         Material_ID = '" + Mat_ID + "' ";
            SqlConnection sqlconn = new SqlConnection(Connection);
            SqlDataAdapter da = new SqlDataAdapter(sqltext, sqlconn);
            DataSet ds = new DataSet();
            da.Fill(ds);

            return ds.Tables[0];
        }
        private DataTable GetDetialMat(string Mat_ID)
        {
            string sqltext = @"SELECT        TB_Material.Material_ID, TB_Material.Materail_name, TB_Unit_Category.Unit_Name
                               FROM           TB_Material Left JOIN
                              TB_Unit_Category ON TB_Material.Unit = TB_Unit_Category.Unit_ID
                               WHERE TB_Material.Material_ID ='" + Mat_ID + "' ";
            SqlConnection sqlconn = new SqlConnection(Connection);
            SqlDataAdapter da = new SqlDataAdapter(sqltext, sqlconn);
            DataSet ds = new DataSet();
            da.Fill(ds);

            return ds.Tables[0];

        }
        protected void ASPxGridView5_RowCommand(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewRowCommandEventArgs e)
        {
            DataTable DataPro = new DataTable();
            DataTable InStock = new DataTable();
            DataTable OutStock = new DataTable();
            if (e.CommandArgs.CommandName == "Cmd_Select")
            {
                string Id = e.CommandArgs.CommandArgument.ToString();
                DataPro = GetDetialMat(Id);
                InStock = GetInstockMat(Id);
                OutStock = GetOutstockMat(Id);
                int NumIN = 0;
                int NumOUT = 0;
                for (int i = 0; i < InStock.Rows.Count; i++)
                {

                    NumIN = NumIN + Convert.ToInt32(InStock.Rows[i]["Material_Count"].ToString());
                }
                for (int i = 0; i < OutStock.Rows.Count; i++)
                {
                    NumOUT = NumOUT + Convert.ToInt32(OutStock.Rows[i]["Material_Count"].ToString());
                }
                txtMatID.Text = DataPro.Rows[0]["Material_ID"].ToString();
                txtMatName.Text = DataPro.Rows[0]["Materail_name"].ToString();
                txtMatStock.Text = (NumIN - NumOUT).ToString();
                txtMatU.Text = DataPro.Rows[0]["Unit_Name"].ToString();

                txtMatCount.Focus();
            }
        }

        
    }
}